<template>
  <div class="page-wapper">
    <!-- 日报管理 -->
    <div class="container">
      <!-- 顶部搜索栏 -->
      <div class="search_bar">
        <div class="left_search">
          <div class="filter_item">
            <div class="label">待办时间：</div>
            <el-date-picker
              v-model="filterData.pickerTimeList"
              type="daterange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD"
              size="small"
            >
            </el-date-picker>
          </div>

          <div class="filter_item">
            <div class="label">是否完成：</div>
            <el-select
              v-model="filterData.isFinish"
              placeholder="请选择"
              size="small"
              clearable
            >
              <el-option
                v-for="item in prepareData.isFinishSelectList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="right_search">
          <el-button-group>
            <el-button
              size="mini"
              :loading="searchBtnLoading"
              type="primary"
              @click="handleSearch"
            >
              搜索
            </el-button>
            <el-button size="mini" @click="handleReset"> 重置 </el-button>
          </el-button-group>
        </div>
      </div>

      <div class="table_options_bar">
        <!-- 标签筛选列 -->
        <el-popover placement="bottom-start" trigger="click" width="600px">
          <div style="display: flex; flex-wrap: wrap">
            <div style="width: 200px">
              <el-checkbox
                v-model="columnsAll.visible"
                @change="tagCheckedChange(columnsAll)"
                >全选
              </el-checkbox>
            </div>
            <template v-for="(item, i) in columns">
              <div v-if="item.title" :key="i" style="width: 200px">
                <el-checkbox
                  v-model="item.visible"
                  :disabled="disabledCancleColumns.includes(item.title)"
                  @change="tagCheckedChange(item)"
                  >{{ item.title }}
                </el-checkbox>
              </div>
            </template>
          </div>

          <template #reference>
            <el-button type="primary" size="mini">筛选列</el-button>
          </template>
        </el-popover>
        <div>
          <el-button size="mini" type="primary" @click="createTableData">
            新建
          </el-button>
          <el-button size="mini" type="danger" @click="deleteAll">
            删除
          </el-button>
        </div>
      </div>

      <div class="table_box f_1">
        <vxe-table
          v-loading="tableLoading"
          :data="tableData"
          :sort-config="{ remote: true }"
          :menu-config="{}"
          :checkbox-config="{ checkField: 'checked', trigger: 'row' }"
          :row-style="rowStyle"
          ref="xTable"
          resizable
          align="center"
          border
          height="100%"
          show-overflow="tooltip"
          highlight-hover-row
          highlight-current-row
          class="xTable"
          @cell-dblclick="cellDbClick"
        >
          <vxe-column type="checkbox" width="60" fixed="left"></vxe-column>

          <vxe-column
            type="seq"
            title="序号"
            width="60"
            fixed="left"
          ></vxe-column>
          <TableColum :colums="tableColum">
            <template #title="{ props }">
              <div style="text-align: left">
                <div
                  :class="{
                    'todo-item-del': props.row.isFinish === '1',
                  }"
                >
                  {{ props.row.title }}
                </div>
              </div>
            </template>
          </TableColum>
          <vxe-column #default="{ row }" width="180" title="操作" fixed="right">
            <div>
              <el-button
                v-if="row.isFinish !== '1'"
                size="mini"
                type="text"
                style="color: #67c23a"
                @click.stop="handleIsFinish(row, '1')"
              >
                完成
              </el-button>

              <el-button
                v-else
                size="mini"
                type="text"
                style="color: #e6a23c"
                @click.stop="handleIsFinish(row, '0')"
              >
                取消完成
              </el-button>

              <el-button
                size="mini"
                type="text"
                @click.stop="editTableDataMethod(row)"
              >
                编辑
              </el-button>

              <el-button
                size="mini"
                type="text"
                style="color: #f78989"
                @click.stop="deleteTableDataMethod(row)"
              >
                删除
              </el-button>
            </div>
          </vxe-column>
        </vxe-table>
      </div>
      <el-pagination
        v-model="pagenationData.current"
        :page-sizes="[500, 100, 50, 15]"
        :page-size="pagenationData.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagenationData.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        small
        style="text-align: center; margin-top: 10px"
      >
      </el-pagination>
    </div>

    <!-- 新建/编辑待办弹框 -->
    <TodoFormDialog
      ref="todoFormDialogRef"
      :prepareData="prepareData"
      @refresh="getTableData"
    />
  </div>
</template>

<script>
import {
  ref,
  reactive,
  onMounted,
  nextTick,
  getCurrentInstance,
  onActivated,
  toRefs,
} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import TableColum from "../../components/TabelTemplate/TableColum.vue";
import TodoFormDialog from "./components/TodoFormDialog.vue";

const initFilterData = () => {
  return {
    pickerTimeList: [],
    startDateTime: null,
    endDateTime: null,
    isFinish: null,
  };
};

export default {
  name: "TodoManage",
  components: { TableColum, TodoFormDialog },
  setup() {
    const { proxy } = getCurrentInstance();
    const $api = proxy.$api;
    const $moment = proxy.$moment;
    const router = useRouter();

    // 搜索绑定的数据
    const filterData = reactive(initFilterData());
    // 真正的搜索条件
    const condition = reactive({});
    const searchBtnLoading = ref(false);

    // 预加载数据
    const prepareData = reactive({
      isFinishSelectList: [],
    });

    const tableState = reactive({
      columnsAll: {
        visible: true,
        title: "全选",
      },
      // 标签筛选列
      columns: [],
      // 列表标签筛选需要禁用筛选的选项
      disabledCancleColumns: ["序号", "操作"],
      xTable: null,
      tableData: [],
      tableLoading: false,
      tableColum: {
        title: {
          title: "待办标题",
          props: { sortable: false, align: "left", "header-align": "center" },
          slotContent: "title",
        },
        todoTime: {
          title: "待办时间",
          props: { sortable: false, width: 130 },
        },
        isFinishLabel: {
          title: "是否完成",
          props: { sortable: false, width: 130 },
        },
      },
    });

    // 分页组件
    const pagenationData = reactive({
      current: 1,
      size: 15,
      total: 0,
    });

    // 重置
    const handleReset = () => {
      const initData = initFilterData();
      Object.keys(filterData).forEach((key) => {
        filterData[key] = initData[key];
      });
      pagenationData.current = 1;
      handleSearch();
    };

    // 搜索
    const handleSearch = () => {
      Object.keys(filterData).forEach((key) => {
        // 解决后端枚举类型传空字符串解析报错的问题
        condition[key] = filterData[key] === "" ? null : filterData[key];
      });
      pagenationData.current = 1;
      getTableData();
    };

    // 获取列表数据
    const getTableData = () => {
      tableState.tableLoading = true;
      const params = {
        ...pagenationData,
        condition: {
          startDateTime: null,
          endDateTime: null,
          ...condition,
        },
      };
      if (condition.pickerTimeList && condition.pickerTimeList.length) {
        params.condition.startDateTime = $moment(condition.pickerTimeList[0])
          .startOf("day")
          .format("YYYY-MM-DD HH:mm:ss");
        params.condition.endDateTime = $moment(condition.pickerTimeList[1])
          .endOf("day")
          .format("YYYY-MM-DD HH:mm:ss");
      }
      $api.todo
        .listPage(params)
        .then((res) => {
          tableState.tableLoading = false;
          tableState.tableData = res.data.list.map((item) => {
            return {
              ...item,
              checked: false,
            };
          });
          pagenationData.total = res.data.total;
          pagenationData.current = res.data.current;
        })
        .catch((err) => {
          tableState.tableLoading = false;
          console.error("tableData error: ", err);
        });
    };

    // 获取任务预加载数据
    const getPreparedData = () => {
      $api.todo
        .preparedData()
        .then((res) => {
          Object.keys(prepareData).forEach((key) => {
            prepareData[key] = res.data[key];
          });
        })
        .catch((err) => {
          console.error("getPreparedData error: ", err);
        })
        .finally(() => {
          // formDialogLoading.value = false;
        });
    };

    // 设置待办是否完成
    const handleIsFinish = (row, isFinish) => {
      ElMessageBox.confirm(
        `确定要${isFinish === "1" ? "完成" : "取消完成"}【${
          row.title.length > 10 ? row.title.slice(0, 10) + "..." : row.title
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          toggleIsFinish(row.id, isFinish);
        })
        .catch(() => {});
    };

    // 删除单个内容
    const deleteTableDataMethod = (row) => {
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除【${
          row.title.length > 10 ? row.title.slice(0, 10) + "..." : row.title
        }】吗？`,
        "提示",
        { type: "warning" }
      )
        .then(() => {
          deleteTableData([row.id]);
        })
        .catch(() => {});
    };

    // 删除全部
    const deleteAll = () => {
      if (!tableState.tableData.length) {
        return ElMessage.warning("没啥可删的");
      }
      const selectedList = tableState.tableData.filter((item) => item.checked);
      if (!selectedList.length) {
        return ElMessage.warning("请选择列表的数据");
      }
      // 二次确认删除
      ElMessageBox.confirm(
        `确定要删除 ${selectedList.length} 条数据吗？`,
        "提示",
        {
          type: "warning",
        }
      )
        .then(() => {
          const ids = selectedList.map((item) => item.id);
          deleteTableData(ids);
        })
        .catch(() => {});
    };

    // 删除内容接口
    const deleteTableData = (ids) => {
      tableState.tableLoading = true;
      $api.todo
        .removeByIds({
          ids,
        })
        .then((res) => {
          console.log("res => ", res);
          ElMessage.success("删除成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("deleteReport error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 设置待办是否完成接口
    const toggleIsFinish = (id, isFinish) => {
      tableState.tableLoading = true;
      $api.todo
        .toggleIsFinish({
          id,
          isFinish,
        })
        .then((res) => {
          ElMessage.success("操作成功！");
          getTableData();
        })
        .catch((err) => {
          console.error("toggleIsFinish error: ", err);
        })
        .finally(() => {
          tableState.tableLoading = false;
        });
    };

    // 筛选列-全选按钮
    const tagCheckedChange = (item) => {
      if (item.title === "全选") {
        // 点击全选操作
        tableState.columns.forEach((cell) => {
          cell.visible = item.visible;
          if (
            !item.visible &&
            tableState.disabledCancleColumns.includes(cell.title)
          ) {
            cell.visible = !item.visible;
          }
        });
      }
      tableState.columnsAll.visible = tableState.columns.every(
        (item) => item.visible
      );
      // 刷新布局
      tableState.xTable.refreshColumn();
    };

    // 动态设置单元行样式
    const rowStyle = ({ rowIndex }) => {
      if (tableState.tableData[rowIndex].checked) {
        return {
          backgroundColor: "pink",
        };
      }
    };

    // 分页-切换页大小
    const handleSizeChange = (size) => {
      pagenationData.size = size;
      getTableData();
    };

    // 分页-切换页数
    const handleCurrentChange = (current) => {
      pagenationData.current = current;
      getTableData();
    };

    const todoFormDialogRef = ref(null);

    // 新建
    const createTableData = () => {
      nextTick(() => {
        todoFormDialogRef.value.open();
      });
    };

    // 编辑内容
    const editTableDataMethod = (row) => {
      nextTick(() => {
        todoFormDialogRef.value.open(row);
      });
    };

    const cellDbClick = ({ row }) => {
      nextTick(() => {
        todoFormDialogRef.value.open(row, true);
      });
    };

    /**
     * 初始化
     */
    getPreparedData();
    handleSearch();

    // 获取所有列配置
    setTimeout(() => {
      nextTick(() => {
        tableState.columns = tableState.xTable.getColumns();
      });
    }, 100);

    // onActivated(() => {
    // });

    return {
      rowStyle,
      searchBtnLoading,
      handleSearch,
      handleReset,
      filterData,
      prepareData,
      deleteTableDataMethod,
      tagCheckedChange,
      getTableData,
      pagenationData,
      deleteAll,
      handleSizeChange,
      handleCurrentChange,
      createTableData,
      editTableDataMethod,
      todoFormDialogRef,
      toggleIsFinish,
      handleIsFinish,
      cellDbClick,
      ...toRefs(tableState),
    };
  },
};
</script>

<style>
.message-title {
  cursor: pointer;
}

.handle-row {
  margin-top: 30px;
}

.todo-item-del {
  text-decoration: line-through;
  color: #999;
}
</style>
